import request from "../utils/request";

// 考试相关类型定义
export interface Question {
  id?: string | number;
  type:
    | "single"
    | "multiple"
    | "judge"
    | "fill"
    | "essay"
    | "choice"
    | "programming"
    | "analysis";
  title: string;
  content: string;
  options?: string[];
  answer: string | string[];
  score: number;
  difficulty: number | string; // 1-简单，2-中等，3-困难，或者 'easy', 'medium', 'hard'
  knowledgePoint: string;
  analysis?: string;
}

export interface Exam {
  id?: number;
  title: string;
  description: string;
  courseId: number;
  teacherId: number;
  startTime: string;
  endTime: string;
  duration: number; // 分钟
  totalScore: number;
  examType: string;
  status: number; // 1-未开始，2-进行中，3-已结束
  passScore: number;
  questions?: Question[];
}

export interface ExamGeneration {
  courseId: number;
  examType: string;
  questionCount: number;
  totalScore: number;
  difficulty: number;
  knowledgePoints: string[];
  duration: number;
  generateWithAI: boolean;
}

export interface AIGenerationRequest {
  courseId: number;
  examType: string;
  questionTypes: {
    single: number;
    multiple: number;
    judge: number;
    fill: number;
    essay: number;
  };
  difficulty: number;
  knowledgePoints: string[];
  totalScore: number;
  requirements?: string;
}

export interface GenerationProgress {
  id: string;
  status: "pending" | "generating" | "completed" | "failed";
  progress: number;
  currentStep: string;
  result?: Question[];
  error?: string;
}

// 添加缺失的接口
export interface AIQuestionRequest {
  topic: string;
  count: number;
  type: string;
  difficulty: string | number;
  requirements?: string;
  knowledgePoints?: string[];
  targetGrade?: string;
  subject?: string;
  customRequirements?: string;
}

export interface ExamComposer {
  id?: string | number;
  title: string;
  description?: string;
  questions: Question[];
  totalScore: number;
  duration: number;
  difficulty: string | number;
  knowledgePoints: string[];
  examName?: string;
  examType?: string;
  targetClass?: string;
  targetCourse?: string;
  questionSelection?: any[];
  aiSuggestions?: any[];
  estimatedDuration?: number;
}

// 构建查询参数
const buildQueryParams = (params: Record<string, any>): string => {
  const searchParams = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== "") {
      searchParams.append(key, String(value));
    }
  });
  return searchParams.toString() ? `?${searchParams.toString()}` : "";
};

export const examApi = {
  // 获取考试列表
  getExams: (params: any) => {
    const queryParams = buildQueryParams(params);
    return request.get(`/api/v1/exam/list${queryParams}`);
  },

  // 获取考试详情
  getExam: (id: number) => {
    return request.get(`/api/v1/exam/${id}`);
  },

  // 创建考试
  createExam: (exam: Partial<Exam>) => {
    return request.post("/api/v1/exam/create", exam);
  },

  // 更新考试
  updateExam: (id: number, exam: Partial<Exam>) => {
    return request.put(`/api/v1/exam/${id}`, exam);
  },

  // 删除考试
  deleteExam: (id: number) => {
    return request.delete(`/api/v1/exam/${id}`);
  },
};

// 题目相关API
export const questionAPI = {
  // 获取题目列表
  getQuestions: (params: any) => {
    const queryParams = buildQueryParams(params);
    return request.get(`/api/v1/question/list${queryParams}`);
  },

  // 获取题目详情
  getQuestion: (id: number) => {
    return request.get(`/api/v1/question/${id}`);
  },

  // 创建题目
  createQuestion: (question: Partial<Question>) => {
    return request.post("/api/v1/question/create", question);
  },

  // 更新题目
  updateQuestion: (id: number, question: Partial<Question>) => {
    return request.put(`/api/v1/question/${id}`, question);
  },

  // 删除题目
  deleteQuestion: (id: number) => {
    return request.delete(`/api/v1/question/${id}`);
  },

  // 批量删除题目
  deleteQuestions: (ids: string[]) => {
    return request.post("/api/v1/question/batch-delete", { ids });
  },

  // 复制题目
  copyQuestion: (id: number) => {
    return request.post(`/api/v1/question/${id}/copy`);
  },

  // 批量复制题目
  copyQuestions: (ids: string[]) => {
    return request.post("/api/v1/question/batch-copy", { ids });
  },

  // AI生成题目
  generateQuestions: (params: any) => {
    return request.post("/api/v1/question/generate-ai", params);
  },

  // 批量生成题目
  batchGenerateQuestions: (requests: any[]) => {
    return request.post("/api/v1/question/batch-generate", { requests });
  },
};

// 智能组卷API
export const examComposerAPI = {
  // 获取AI建议
  getAISuggestions: (params: any) => {
    const queryParams = buildQueryParams(params);
    return request.get(`/api/v1/exam/ai-suggestions${queryParams}`);
  },

  // 智能选择题目
  smartSelection: (params: any) => {
    return request.post("/api/v1/exam/smart-selection", params);
  },

  // 保存组卷
  saveComposition: (examData: any) => {
    return request.post("/api/v1/exam/save-composition", examData);
  },

  // 预览组卷
  previewComposition: (params: any) => {
    return request.post("/api/v1/exam/preview-composition", params);
  },

  // 获取推荐题目
  getRecommendations: (params: any) => {
    const queryParams = buildQueryParams(params);
    return request.get(`/api/v1/exam/recommendations${queryParams}`);
  },

  // 分析试卷难度
  analyzeDifficulty: (questionIds: number[]) => {
    return request.post("/api/v1/exam/analyze-difficulty", { questionIds });
  },

  // 获取知识点覆盖率
  getKnowledgeCoverage: (params: any) => {
    return request.post("/api/v1/exam/knowledge-coverage", params);
  },
};

// 模板API
export const templateAPI = {
  // 获取试卷模板列表
  getTemplates: (params?: any) => {
    const queryParams = params ? buildQueryParams(params) : "";
    return request.get(`/api/v1/exam/templates${queryParams}`);
  },

  // 获取模板详情
  getTemplate: (id: number) => {
    return request.get(`/api/v1/exam/templates/${id}`);
  },

  // 创建模板
  createTemplate: (template: any) => {
    return request.post("/api/v1/exam/templates", template);
  },

  // 更新模板
  updateTemplate: (id: number, template: any) => {
    return request.put(`/api/v1/exam/templates/${id}`, template);
  },

  // 删除模板
  deleteTemplate: (id: number) => {
    return request.delete(`/api/v1/exam/templates/${id}`);
  },

  // 应用模板
  applyTemplate: (templateId: number, params: any) => {
    return request.post(`/api/v1/exam/templates/${templateId}/apply`, params);
  },

  // 从试卷创建模板
  createFromExam: (examId: number, templateData: any) => {
    return request.post("/api/v1/exam/templates/from-exam", {
      examId,
      ...templateData,
    });
  },
};
